package com.chookss.video

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import com.alibaba.fastjson.JSON
import com.chookss.R
import com.chookss.base.StaticClass
import com.chookss.tools.FileUtilss
import com.chookss.tools.Utils
import com.johnrambo.ktea.common.parseArray
import kotlinx.android.synthetic.main.fragment_video_search.*
import java.io.File
import java.util.*

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/26 18:04
 * Note:
 */
class VideoSearchFragment : Fragment() {
    val searchHistory by lazy { SearchHistory(requireContext(), 5) }
    lateinit var historyAdapter: ArrayAdapter<String>
    var videoType = 0 //2发布图文过来的0默认
    val onKeyListener = View.OnKeyListener { v, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
            var text = (v as EditText).text.toString()
            if (!TextUtils.isEmpty(text)) {
                searchHistory.add(text)
                notifyListViewChanged()
                v.setText("")
                searchVideo(text)
            }
        }
        false
    }
    fun toSearch(content:String) {
        searchHistory.add(content)
        notifyListViewChanged()
        searchVideo(content)
    }
    fun addSearch(content:String) {
        searchHistory.add(content)
        notifyListViewChanged()
    }
    private fun searchVideo(text: String) {
        startActivity(Intent(activity, SearchVideoResultActivity::class.java).apply {
            putExtra("keyword", text)
            putExtra("type", videoType)
        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_video_search, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        historyAdapter = createAdapter()
        listView.adapter = historyAdapter

        var header = View.inflate(requireActivity(), R.layout.item_video_search_footer, null)
        var ll_clear=header.findViewById<LinearLayout>(R.id.ll_clear)
        listView.addHeaderView(header)
        ll_clear.setOnClickListener {
            searchHistory.clear()
            notifyListViewChanged()
        }
        listView.setOnItemClickListener { parent, view, position, id ->
            if(position!=0){
                println(parent.adapter.getItem(position).toString())
                searchVideo(parent.adapter.getItem(position).toString())
            }
        }
    }

    private fun createAdapter():ArrayAdapter<String> {
        return object:ArrayAdapter<String>(requireActivity(), R.layout.item_search_layout, R.id.tvBowler, searchHistory.searchHistoryList){
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                var view = super.getView(position, convertView, parent)
                view.findViewById<LinearLayout>(R.id.ivBowlerDel).tag = position
                if (convertView == null) {
                    view.findViewById<LinearLayout>(R.id.ivBowlerDel).setOnClickListener {
                        searchHistory.removeAt(it.tag as Int)
                        historyAdapter.notifyDataSetChanged()
                    }
                }
                return view
            }
        }
    }

    private fun notifyListViewChanged() {
        historyAdapter.setNotifyOnChange(false)
        historyAdapter.clear()
        historyAdapter.filter.filter("");
        historyAdapter.addAll(searchHistory.searchHistoryList)
        historyAdapter.notifyDataSetChanged()
    }

    fun setType(videoType:Int) {
       this.videoType=videoType
    }
    fun setContent(content:String) {
        historyAdapter.filter.filter(content)
    }

    class SearchHistory(var context: Context, var maxCount:Int) {
        val historyFile by lazy {
            File(context.filesDir,
                Utils.getCacheName(context, StaticClass.VIDEO_HISTORY))
        }
        val searchHistoryList = ArrayList<String>()
        init {
            try {
                var text = FileUtilss.readFile(historyFile, "utf-8")
                if(!Utils.isNull(text)){
                    searchHistoryList.addAll(text.parseArray<String>())
                }

                checkMaxCount()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun clear() {
            searchHistoryList.clear()
            saveSearchHistory()
        }
        fun add(text:String) {
            searchHistoryList.remove(text)
            searchHistoryList.add(0, text)
            saveSearchHistory()
        }
        fun removeAt(index:Int) {
            searchHistoryList.removeAt(index)
            saveSearchHistory()
        }

        private fun saveSearchHistory() {
            checkMaxCount()
            try {
                var text = JSON.toJSONString(searchHistoryList)
                FileUtilss.write(historyFile.absolutePath, text.toByteArray(Charsets.UTF_8))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        private fun checkMaxCount() {
            while (searchHistoryList.size > maxCount) {
                searchHistoryList.removeLast()
            }
        }
    }

}